package com.jokey.vue.controller;

import com.jokey.vue.dto.HrRoleUpdateReq;
import com.jokey.vue.dto.PasswordUpdateReq;
import com.jokey.vue.model.Hr;
import com.jokey.vue.model.RespBean;
import com.jokey.vue.model.Role;
import com.jokey.vue.service.HrService;
import com.jokey.vue.service.RoleService;
import com.jokey.vue.utils.HrUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * @author: JokeyZheng
 * @email: zhengjingfeng@ruqimobility.com
 * @created: 2021/11/30 20:09
 * @version: v1.0.0
 */
@RestController
@RequestMapping("/hr")
public class HrInfoController {

    @Resource
    private HrService hrService;

    @Resource
    private RoleService roleService;

    /**
     * 获取当前的HR信息
     *
     * @return
     */
    @GetMapping("/info")
    public RespBean<Hr> getCurrentHr() {
        Hr hr = HrUtils.getCurrentHr();
        return RespBean.ok(hr);
    }

    /**
     * 修改HR信息
     *
     * @param hr
     * @return
     */
    @PutMapping("/info")
    public RespBean updateInfo(@RequestBody Hr hr) {
        boolean update = hrService.updateById(hr);
        if (update) {
            Authentication authentication = HrUtils.getCurrentHrAuthentication();
            SecurityContextHolder.getContext().setAuthentication(
                    new UsernamePasswordAuthenticationToken(
                            hr,
                            authentication.getCredentials(),
                            authentication.getAuthorities()
                    ));
            return RespBean.ok("更新成功");
        }
        return RespBean.error("更新失败");
    }

    /**
     * 修改密码
     *
     * @param password
     * @return
     */
    @PutMapping("/password")
    public RespBean updateHrPassword(@Valid @RequestBody PasswordUpdateReq password) {
        return hrService.updateHrPassword(password) ? RespBean.ok("更新成功!") : RespBean.error("更新失败!");
    }

    /**
     * 查询HR信息
     *
     * @param keywords
     * @return
     */
    @GetMapping("/list")
    public RespBean<List<Hr>> getAllHrs(String keywords) {
        return RespBean.ok(hrService.getAllHrs(keywords));
    }

    /**
     * 获取角色数据
     *
     * @return
     */
    @GetMapping("/roles")
    public RespBean<List<Role>> getAllRoles() {
        return RespBean.ok(roleService.list());
    }

    /**
     * 修改HR的角色
     *
     * @param req
     * @return
     */
    @PutMapping("/role")
    public RespBean updateHrRole(@Valid @RequestBody HrRoleUpdateReq req) {
        return hrService.updateHrRole(req) ? RespBean.ok("更新成功!") : RespBean.error("更新失败!");
    }
}
